package com.sdy.kzyy.pc.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.kzyy.biz.dto.BookingSituationDTO;
import com.sdy.kzyy.biz.dto.StoreDTO;
import com.sdy.kzyy.biz.model.Manager;
import com.sdy.kzyy.biz.service.BookingSituationService;
import com.sdy.kzyy.biz.service.ManagerService;
import com.sdy.kzyy.pc.util.Constants;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: 王越洋
 * @version: v1.0
 * @description: com.sdy.kzyy.web.controller.web
 * @date:2020/3/25
 */

@Slf4j
@RestController
@RequestMapping("/getBookingSituation")
@Api(tags = "口罩预约情况")
public class BookingSituationController extends BaseController {
    @Autowired
    private BookingSituationService bookingSituationService;
    @Autowired
    private ManagerService managerService;

    @GetMapping("/getBookingPage")
    @ApiOperation(value = "口罩预约情况分页接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "receiveStatus", value = "预约状态 1:未取货 2:已取货 3:已过期"),
            @ApiImplicitParam(name = "name", value = "预约人姓名/药店名"),
            @ApiImplicitParam(name = "startTime", value = "申请时间段/开始"),
            @ApiImplicitParam(name = "endTime", value = "申请时间段/结束"),
    })
    public Response getBookingPage(HttpServletRequest request, Integer receiveStatus, String name, Date startTime, Date endTime,
                                   Page<BookingSituationDTO> page) {
        if (name != null){
            try {
                name = URLDecoder.decode(name, "UTF-8");
            }catch (Exception e) {
                return Response.error("");
            }
        }
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Manager byId = managerService.getById(userId);
        if (byId == null){
            Response.error("当前Session 不存在");
        }
        String storeCode = byId.getStoreCode();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String startTimeStr = null;
        String endTimeStr = null;
        if (null != startTime) {
            startTimeStr = format.format(startTime) +" "+"00:00:00";
            endTimeStr = format.format(endTime)+" "+"23:59:59";
        }
        List<BookingSituationDTO> bookingPage = bookingSituationService.getBookingPage(storeCode, receiveStatus, name, startTimeStr, endTimeStr, page);
        Integer bookingSize = bookingSituationService.getBookingSize(storeCode, receiveStatus, name, startTimeStr, endTimeStr);

        for (BookingSituationDTO b:bookingPage) {
            if (b.getOrderStatus() == 1){
                b.setReceiveStatus(3);
            }
            b.setAddress(b.getAreaName()+b.getAddress());
        }
        IPage<BookingSituationDTO> storeVoPage = new Page<BookingSituationDTO>(page.getCurrent(), page.getSize(), bookingSize).setRecords(bookingPage);
        return Response.success(storeVoPage);
    }

    @GetMapping("/getBookingExcel")
    @ApiOperation(value = "口罩预约情况Excel导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "receiveStatus", value = "预约状态 1:未取货 2:已取货 3:已过期"),
            @ApiImplicitParam(name = "name", value = "预约人姓名/药店名"),
            @ApiImplicitParam(name = "startTime", value = "申请时间段/开始"),
            @ApiImplicitParam(name = "endTime", value = "申请时间段/结束"),
    })
    public void getBookingPage(HttpServletRequest request, Integer receiveStatus, String name, Date startTime, Date endTime, HttpServletResponse response) throws IOException, BizException {
        if (name != null){
            try {
                name = URLDecoder.decode(name, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        Integer userId = getUserId(request, Constants.SESSION_WEB_USER_ID);
        Manager byId = managerService.getById(userId);
        if (byId == null){
            Response.error("当前Session 不存在");
        }
        String storeCode = byId.getStoreCode();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String startTimeStr = null;
        String endTimeStr = null;
        if (null != startTime) {
            startTimeStr = format.format(startTime) +" "+"00:00:00";
            endTimeStr = format.format(endTime)+" "+"23:59:59";
        }
        List<BookingSituationDTO> bookingExcel = bookingSituationService.getBookingPage(storeCode,receiveStatus, name, startTimeStr, endTimeStr);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = sdf.format(new Date());
        String excelName = URLDecoder.decode("口罩预约情况.xlsx", "UTF-8");
        String fileName = date + excelName;
        for (BookingSituationDTO b:bookingExcel) {
            Assert.isNull(b.getOrderStatus(),"订单状态 有问题");
            if (b.getOrderStatus() == 1){

                b.setReceiveStatus(3);
            }
            if (b.getReceiveStatus() != null) {
                b.setReceiveStatu(b.getReceiveStatus()== 1 ? "未领取" : b.getReceiveStatus() == 2 ? "已领取" : "已失效");
            }
            b.setAddress(b.getAreaName()+" "+b.getAddress());
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
        EasyExcel.write(response.getOutputStream(), BookingSituationDTO.class).sheet("口罩预约情况").doWrite(bookingExcel);
    }
}
